package com.example.config.security;

import com.example.entity.Admin;
import com.example.entity.RespBean;
import com.example.service.IAdminService;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 当未登录或者token失效时访问接口时，自定义的返回结果
 *
 * @author: liu
 * 2022-03-14-17:11
 **/
@Component
public class RestAuthorizationEntryPoint implements AuthenticationEntryPoint {
//    @Autowired
//    private IAdminService iAdminService;

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse
            response, AuthenticationException e) throws IOException, ServletException {
//        if(iAdminService.getAdminByUserName(username) == null){
//            RespBean.error("用户名不存在");
//        }

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
//        System.out.println("RestAuthorizationEntryPoint: out is " +out);
        RespBean bean = RespBean.error("尚未登录，请登录！");
        bean.setCode(401);
        out.write(new ObjectMapper().writeValueAsString(bean));
        out.flush();
        out.close();
    }
}
